#http://infotrac.galegroup.com/itweb/cnruc?db=GDC
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import json
from bs4 import BeautifulSoup
import urllib


def buildingParameters(data):
    data["log"].append("###")

    typeCorr = {
        "TI": "1",
        "AU": "2",
        "KY": "3"
    }

    logCorr = {
        "and": "1",
        "or": "2",
        "not": "3",
        "###": "1"
    }

    # print(data)
    # exit()

    tempStr = []
    for i in range(len(data["values"])):
        try:
            strr = "{}^1^{}^{}".format(typeCorr[data["type"][i]],logCorr[data["log"][i]],urllib.parse.quote(data["values"][i]))
            tempStr.append(strr)
        except:
            raise

    if len(tempStr) == 0:
        return -1

    strr = ''
    for value in tempStr:
        strr += value + "|"

    return strr.strip().strip("|").strip()

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []

    soup = BeautifulSoup(response.text, "html5lib")

    lis = soup.select("table[class='searchResult content'] > tbody > tr")

    for li in lis:

        tempData = resultData()

        try:
            tempData["titleName"] = li.select(".document_title > a")[0].text.strip()
        except:
            pass

        try:
            tempData["titleHref"] = "http://gdc.galegroup.com" + li.select(".document_title > a")[0]["href"]
        except:
            pass

        try:
            tempData["source"] = li.select(".product_name")[0].text.strip()
        except:
            pass

        allData.append(tempData)

    return allData

def getData(keyword):
    proxies = {
        "http": "http://qf:qf3.1415@202.112.118.7:10086/"
    }

    headers = {
        'Proxy-Connection': 'keep-alive',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://gdc.galegroup.com/gdc/artemis?p=GDCS&u=cnruc',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('action', '1'),
        ('u', 'cnruc'),
        ('p', 'GDCS'),
        ('javax.portlet.action', 'doSearch'),
        ('query', 'OQE {}'.format(keyword)),
        ('activityType', 'BasicSearch'),
        ('display-query', 'OQE {}'.format(keyword)),
        ('displayGroupName', ''),
        ('catId', ''),
        ('basicSearchIndex', 'OQE'),
        ('prodId',
         'BBCN:NCUK:AMFN:GDSC:AHSI:APOA:BPHC:BNCN:CFER:CPPC:ECCO:ILN:INDP:LBRT:MLFP:MMLF:MOML:MMLP:MMLT:MOME:NCCO:NCNP:PIPO:PNCH:SABN:SMIT:TTDA:TLSH:USDD:SCRB'),
        ('csProduct',
         ['BBCN', 'NCUK', 'AMFN', 'GDSC', 'AHSI', 'APOA', 'BPHC', 'BNCN', 'CFER', 'CPPC', 'ECCO', 'ILN', 'INDP', 'LBRT',
          'MLFP', 'MMLF', 'MOML', 'MMLP', 'MMLT', 'MOME', 'NCCO', 'NCNP', 'PIPO', 'PNCH', 'SABN', 'SMIT', 'TTDA',
          'TLSH', 'USDD', 'SCRB']),
        ('search_input', keyword),
        ('find', '\u68C0\u7D22'),
    )

    response = requests.get('http://gdc.galegroup.com/gdc/artemis/PageFinderPortletPage/PageFinderPortletWindow',
                            headers=headers, params=params, proxies=proxies)

    allData = formData(response)

    return allData

def getCookies():

    headers = {
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
    }

    params = (
        ('db', 'BIG'),
    )
    proxies = {
        "http": "http://qf:qf3.1415@202.112.118.7:10086/"
    }
    s = requests.session()
    s.get('http://infotrac.galegroup.com/itweb/cnruc', headers=headers, params=params,proxies=proxies)

    cookies = s.cookies.get_dict()

    return cookies

def index(request):
    data = json.loads(request.POST.get('data', '1'))

    # cookies = getCookies()

    allData= getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")